package com.ali.pogo;

import com.ali.sqlSession.SqlSession;

import java.lang.reflect.Method;

public class MapperMethod {
    private Class<?> mapperInterface;
    private Method method;
    private Configuration configuration;

    public MapperMethod(Class<?> mapperInterface, Method method, Configuration configuration) {
        this.mapperInterface = mapperInterface;
        this.method = method;
        this.configuration = configuration;
    }

    public Object execute(SqlSession sqlSession, Object[] args) throws Exception {
        /**
         * 获取sql type（select insert update delete）
         */
        MappedStatement mappedStatement = this.resolveMappedStatement(this.mapperInterface, this.method, this.configuration);
        SqlCommandType sqlType = mappedStatement.getSqlType();
        switch (sqlType){
            case INSERT:
                return sqlSession.insert(mappedStatement.getId(),args);
            case DELETE:

                return sqlSession.delete(mappedStatement.getId(),args);
            case UPDATE:
                return sqlSession.update(mappedStatement.getId(),args);
            case SELECT:
                return sqlSession.selectList(mappedStatement.getId(),args);
            default:
                throw new Exception("invalid function");
        }



    }

    /**
     * 根据接口的名称和方法的名称组成statementId 看configuration中解析的是否包含
     * 愿方法还包含 如果当前接口没有包含此方法， 就去就去实现的其他接口中查找
     * @param mapperInterface
     * @param method
     * @param configuration
     * @return
     */
    public MappedStatement resolveMappedStatement(Class<?> mapperInterface,Method method,Configuration configuration){
        String name = method.getName();
        String statementId = mapperInterface.getName() + "." + name;
        if(configuration.hasStatementId(statementId)){
            return configuration.getMappedStatementMap().get(statementId);
        }
        return null;
    }

    /**
     * 将参数转换成sql命令参数
     * @param args
     */
    public void convertArgsToSqlCommandParam(Object[] args){

    }

}
